package com.normal.utils.sp

import android.os.Parcelable
import android.util.Log
import com.hnly.djdl.BuildConfig
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 *
 *@author jiang create by 2022/11/9 20 26
 */
class ParcelableProperty<T : Parcelable>(private val key: String, private val def: T) :
    ReadWriteProperty<SpData, T?> {
    var data: T? = null
    override fun getValue(thisRef: SpData, property: KProperty<*>): T {
        if (BuildConfig.DEBUG) {
            Log.i("ParcelableProperty", "存储,$data")
        }
        if (data == null) {
            return thisRef.mmkv.decodeParcelable(key, def.javaClass) ?: def
        }
        return data!!
    }

    override fun setValue(thisRef: SpData, property: KProperty<*>, value: T?) {
        if (value != null) {
            data = value
            thisRef.mmkv.encode(key, value)
        }
    }
}